package com.debao;

import cn.hutool.json.JSONObject;
import com.debao.common.annotation.Anonymous;
import com.debao.common.constant.CacheConstants;
import com.debao.common.constant.Constants;
import com.debao.common.constant.WechatConstants;
import com.debao.common.core.domain.AjaxResult;
import com.debao.common.core.domain.model.RegisterBody;
import com.debao.common.core.redis.RedisCache;
import com.debao.common.utils.SecurityUtils;
import com.debao.common.wechat.WechatUtils;
import com.debao.dto.CodeLogin;
import com.debao.dto.LoginDto;
import com.debao.framework.web.service.SysLoginService;
import com.debao.framework.web.service.SysRegisterService;
import com.debao.system.domain.Banner;
import com.debao.system.domain.Coach;
import com.debao.system.domain.Stadium;
import com.debao.system.service.*;
import lombok.SneakyThrows;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 授权登录
 */
@RestController
@RequestMapping("/api/auth")
public class ApiAuth {
    @Resource
    private SysLoginService loginService;
    @Resource
    private SysRegisterService registerService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IConfigService configService;
    @Resource
    private RedisCache redisCache;

    /**
     * 授权登录
     *
     * @param dto
     * @return
     */
    @SneakyThrows
    @Anonymous
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Validated LoginDto dto) {

        // 获取appid
        String appid = configService.selectValueByKey(WechatConstants.APP_ID);
        // 获取secret
        String secret = configService.selectValueByKey(WechatConstants.APP_SECRET);
        // 获取token
        String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
        if (token == null) {
            return AjaxResult.error("获取token失败");
        }
        // 获取openId
//        String openId = WechatUtils.getOpenId(dto.getLoginCode(), appid, secret);
        JSONObject sessionData = WechatUtils.getSessionData(dto.getLoginCode(), appid, secret);
        String openId = sessionData.getStr("openid");
        String unionId = sessionData.getStr("unionid");

        // 获取phone 的方法
        String phone = WechatUtils.authenticatePhoneNumber(dto.getCode(), token);
        // 获取用户是否已存在【手机号是否被注册】
        boolean isExist = userService.isExistUser(phone);
        // 用户不存在
        if (!isExist) {
            // 开始注册用户 | 注册成功返回 TOKEN
            registerService.register(phone, openId,unionId);
        }
        //用户存在存在更新unionId
        userService.updateUserUnionid(phone, unionId,openId);
        AjaxResult ajax = AjaxResult.success();
        // 用户存在 | 返回用户的token信息
        ajax.put(Constants.TOKEN, loginService.login(phone, Constants.DEFAULT_PASSWORD));
        return ajax;
    }

    @SneakyThrows
    @Anonymous
    @PostMapping("/phoneLogin")
    public AjaxResult phoneLogin(@RequestBody @Validated CodeLogin dto) {
        //缓存中取动态验证码
        String cacheCode = redisCache.getCacheObject(CacheConstants.SMS_CODE + dto.getPhone());
        //判断 cacherCode 是否为空
        if (cacheCode == null) {
            return AjaxResult.error("验证码已过期");
        }
        // 判断验证码是否正确
        if (!cacheCode.equals(dto.getCode())) {
            return AjaxResult.error("验证码错误");
        }
        // 获取appid
        String appid = configService.selectValueByKey(WechatConstants.APP_ID);
        // 获取secret
        String secret = configService.selectValueByKey(WechatConstants.APP_SECRET);
        // 获取token
        String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
        if (token == null) {
            return AjaxResult.error("获取token失败");
        }
        // 获取openId
//        String openId = WechatUtils.getOpenId(dto.getLoginCode(), appid, secret);
        JSONObject sessionData = WechatUtils.getSessionData(dto.getLoginCode(), appid, secret);
        String openId = sessionData.getStr("openid");
        String unionId = sessionData.getStr("unionid");

        // 获取用户是否已存在【手机号是否被注册】
        boolean isExist = userService.isExistUser(dto.getPhone());
        // 用户不存在
        if (!isExist) {
            // 开始注册用户 | 注册成功返回 TOKEN
            registerService.register(dto.getPhone(), openId,unionId);
        }
        //用户存在存在更新unionId
        userService.updateUserUnionid(dto.getPhone(), unionId,openId);
        AjaxResult ajax = AjaxResult.success();
        // 用户存在 | 返回用户的token信息
        ajax.put(Constants.TOKEN, loginService.login(dto.getPhone(), Constants.DEFAULT_PASSWORD));
        return ajax;
    }


}
